<?php  global $CFG, $USER, $COURSE, $PR_ACTIVITY; ?>

<link rel="stylesheet" href="<?php echo $CFG->baseurl?>/jwc/jquery/ui/themes/flora/flora.dialog.css" type="text/css" media="screen" title="Flora (Default)">
<link rel="stylesheet" href="<?php echo $CFG->baseurl?>/jwc/jquery/ui/themes/flora/flora.resizable.css" type="text/css" media="screen" title="Flora (Default)">
<link rel="stylesheet" href="<?php echo $CFG->baseurl?>/jwc/jquery/ui/themes/flora/flora.draggable.css" type="text/css" media="screen" title="Flora (Default)">

<script type="text/javascript" src="<?php echo $CFG->baseurl?>/uuid/LightweightGenerator.js"></script>
<script type="text/javascript" src="<?php echo $CFG->baseurl?>/jwc/js/smileys.js"></script>
<script type="text/javascript" src="<?php echo $CFG->baseurl?>/jwc/js/conversation.js"></script>
<script type="text/javascript" src="<?php echo $CFG->baseurl?>/jwc/js/sack.js"></script>
<script type="text/javascript" src="<?php echo $CFG->baseurl?>/jwc/js/asyn.js"></script>

<? if($CFG->cp_skype_link): ?>
<script type="text/javascript" src="http://download.skype.com/share/skypebuttons/js/skypeCheck.js"></script>
<?endif;?>

<script type="text/javascript" src="<?php echo $CFG->baseurl?>/jwc/jquery/jquery-1.2.6.js"></script>
<script type="text/javascript" src="<?php echo $CFG->baseurl?>/jwc/jquery/jquery.fieldselection.js"></script>
<script type="text/javascript" src="<?php echo $CFG->baseurl?>/jwc/jquery/jquery.hotkeys.js"></script>
<script type="text/javascript" src="<?php echo $CFG->baseurl?>/jwc/jquery/ui/source/ui.core.js"></script>
<script type="text/javascript" src="<?php echo $CFG->baseurl?>/jwc/jquery/ui/source/ui.dialog.js"></script>
<script type="text/javascript" src="<?php echo $CFG->baseurl?>/jwc/jquery/ui/source/ui.resizable.js"></script>
<script type="text/javascript" src="<?php echo $CFG->baseurl?>/jwc/jquery/ui/source/ui.draggable.js"></script>
<script type="text/javascript" src="<?php echo $CFG->baseurl?>/jwc/jquery/jquery.bgiframe.js"></script>

<script type="text/javascript">
	<?php include("js/json.js"); ?>
	document.body.setAttribute('class', document.body.getAttribute('class') + ' yui-skin-sam');
	var cp_basepath = '<?php echo $CFG->baseurl?>';
	var open_wins = new Array();

	// variable to contain saved data if it exists... get_data called below
	var mydata = {};
	var prototypeWin;
	var debug = 0;

	var skype_enabled = <?php echo $CFG->cp_skype_link ?>;
	var wb_enabled = <?php echo $CFG->cp_wb_link ?>;
	var wb_active = 0;
	var wb_id = null;
	var av_enabled = <?php echo $CFG->cp_av_link ?>;
	var myself = '<?php echo $USER->username?>';
	var myname = '<?php echo $USER->firstname . " " . $USER->lastname ?>';
	var usernames = new Array();

	// TOKEN para conferencia
	var avToken = "";

	function dalert(str)
	{
		if (debug)
			alert(str);
	}


	function time()
	{
		var x = new Date();
		return x.getTime()/1000;
	}
	
function new_window(wname)
{
	dalert('<? echo get_string('dbgCreatingNewWin', 'block_presence')?>:' + wname);

	if (get_window(wname))
	{
		unminimize_window(wname);
		return true;
	}
	
	var winName = wname.replace("#", "");
	var dWidth = 180;
	var dHeight= 400;

	
	$("<div>")
	.addClass("flora")
	.attr("id", winName)
	.css({
		marginTop: '0px',
		marginLeft: '8px',
		textAlign: 'left',
		width:dWidth + 25
	})
	.append(
		$('<div>')
		.attr("id", winName+"_main")
		.css(
		{
			padding: '0px',
			margin:'0 auto',
			textAlign: 'left',
			overflow: "hidden", 
			backgroundColor: "#fff"
		})
		.append(
			$("<div>")
			.attr("id", winName+"_conv")
			.css({
				padding: '0px',
				margin:'0px',
				textAlign: 'left',
				overflow: "auto",
				'width'	 : (dWidth + 24),
				height: dHeight - 80
			})
		)
		.append(
			$("<div>")
			.attr("id", winName+"_menus")
			.css({
				'width'	 : (dWidth + 23),
				'margin' : '0 auto',
				textAlign: 'right'
			})
			.append(
				$('<input type="image" src="<?php echo $CFG->baseurl?>/jwc/images/smileys.gif" />')
				.click(function(e){
					abreSmileys(e, winName, '<? echo $CFG->baseurl?>/jwc/smileys/');
				})
			)
			.append(
				$('<input type="image" src="<?php echo $CFG->baseurl?>/jwc/images/save.png" />')
				.click(function(){
					save_conv(winName)
				})
			)
		)
		.append(
			$('<textarea></textarea>')
			.css({
				'border' : '1px #dedede solid',
				padding:'0px', 
				textAlign: 'left', 
				margin:'0px', 
				'width'	 : (dWidth + 23),
				height: '80px', 
				overflow:'hidden'
			})
			.attr("id", winName+"_ef")
		)
		
	)
	.dialog({
		title: winName,
		width: dWidth + 40,
		height: dHeight + 60,
		minWidth: dWidth + 40,
		minHeight: dHeight + 60,
		dragStart:function()
		{
			$(this).css("opacity", .5);
		},
		dragStop: function()
		{
			$(this).fadeTo("fast", 1);
		},
		resizeStart: function()
		{
			$(this).find("div#"+winName+"_main").hide();
		},
		resizeStop: function()
		{
			$(this)

			.find("div#"+winName+"_main")
			.css({
				width: $(this).width() - 15,
				height: $(this).height() - 50
			})

			$(this)
			.find("div#"+winName+"_conv")
			.css({
				width: $(this).find("div#"+winName+"_main").width(),
				height: $(this).height() - 135
			})

			$(this)
			.find("div>textarea")
			.css({
				width: $(this).find("div#"+winName+"_main").width() - 2
			})

			$(this)
			.find("div#"+winName+"_menus")
			.css({
				width: $(this).find("div#"+winName+"_main").width()
			})
			
			$(this)
			.find("div#"+winName+"_main")
			.show();
		},
		open: function()
		{
			var winDisplay = $("#"+winName).css("display");

			if(winDisplay == "none")
				$("#"+winName).show();
			
			$("#"+winName+"_roster_entry").empty();
		},
		close: function()
		{
			
			minimize_window(winName)
		}
	});
	
	$.hotkeys.add('Shift+return', {type: "keydown"}, function(){
		$("#"+winName+"_ef:visible").focus().replaceSelection('\n', true);
	});
	
	$.hotkeys.add('return', {type: "keydown"}, function()
	{ 
		var textarea = $("#"+winName+"_ef:visible");
		
		if(textarea)
		{
			if(textarea.val() != "")
			{
				var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&amp;%@!\-\/]))?)/gi;
				msg = textarea.val();
				
				msg = "<div>"+msg+"</div>";
				msg = $(msg).text();
				msg = msg.replace(regexp,'<a href="$1" target="_blank">$1</a>')
				msg = msg.replace(/\n/gim, "<br />")
				
				
				
				messages.push({message: msg, to: winName});
				send();
				textarea.val("")
			}
		}
		return false;
	});
			
	open_wins.push({w: wname, c: new Conversation(myname, wname, wname)});	
	return open_wins[open_wins.length-1];
}

function get_window_index(name)
{
	for (var i = 0; i < open_wins.length; i++)
	{
		if (open_wins[i]['w'] == name)
		{
			return i;
		}
	}
}

function get_window(name)
{
	return open_wins[get_window_index(name)];
}


function close_window(name)
{
	// XXX: leave a groupchat, if it's a group chat..?

	// really really close a window
	destroy_window(name);
	open_wins.splice(get_window_index(name),1);


	// here we trigger the save data call, in order to make sure data from the conversation is purged from the server
	save_all_data();
}

function minimize_window(name)
{
	// hide the window..
	var twin = get_window(name);
	
	$("#"+twin.w).hide();
	

	// XXX: set the marker on the roster to show there is a minimized window 
	// XXX: perhaps the print_roster should rather check to see if the rosterentry has a minimized window?
	//var rosterentry = document.getElementById(name + '_roster_entry');
	// Presents the marker only if exists conversation...
	var roster_entry = "#"+name + '_roster_entry';

	if($("#"+twin.w+"_conv").html() != "")
	{ 
		$(roster_entry).html('<img src="<?php echo $CFG->baseurl?>/lullacons/mini-comment.png" />');
		intervaler(name + '_roster_entry', '<img src="<?php echo $CFG->baseurl?>/lullacons/mini-comment.png" />', '<img src="<?php echo $CFG->baseurl?>/lullacons/alert.png" />', 10);
	}
}

function unminimize_window(name)
{
	// display the window
	var twin = get_window(name);
	//$("#"+twin.w).css("display") = 'block';
	$("#"+twin.w).dialog('open');
	
	// remove marker for minimized window
	$("#"+name+ '_roster_entry').empty();
	
	mywin.c.fixscroll();
	return true;
}

function focus_window()
{
	var wc;
	var name;

	if (arguments.length)
		name = arguments[0];
	
	for (var i = 0; i < open_wins.length; i++)
	{
		if (name)
		{
			status_msg('<? echo get_string('dbgSettingFoccus', 'block_presence')?>:' + name);
			if (open_wins[i]['w'] == name)
			{
				$("#"+open_wins[i]['w']).dialog(true);
				wc = open_wins[i]['w'];
			}
			else
			{
				//$("#"+open_wins[i]['w']).hasfocus = false;
			}
		}
		else
		{
			status_msg('hasfocus=' + open_wins[i]['w'].hasfocus);
			if ($("#"+open_wins[i]['w']).hasfocus)
				wc = $("#"+open_wins[i]['w']);
		}
	}
	//document.getElementById(wc.wname + '_ef').focus();
}

function status_msg(msg)
{
	$('#status-layer').empty().append(msg);
}

function expand_link(vis)
{
	if (vis != 'block')
		return '<a href="javascript:void(0);" onclick="tvis_contactlist()"><img src="<?php echo $CFG->baseurl?>/lullacons/arrow-single-down-green.png" border="0" /></a>';
	else
		return '<a href="javascript:void(0);" onclick="tvis_contactlist()"><img src="<?php echo $CFG->baseurl?>/lullacons/arrow-single-up-green.png" border="0" /></a>';
}

function tvis_contactlist()
{
	var rosterelem = $('#contact-list');

	var rosvis = rosterelem.css("display");

	if (rosvis != 'block')
	{
		rosterelem.css("display", 'block');
	}
	else
	{
		rosterelem.css("display", 'none');
	}
	$('#fold-menu').empty().append(expand_link(rosterelem.css("display")));
}

var logged_in = 1;
var roster = new Array();
var roster_info = new Array();
function format_info(infohash)
{
	var ret = "";
	if (infohash["skype"])
	{
		if (skype_enabled)
			ret += '<a href="skype:' + infohash["skype"] + '?call"><img src="http://mystatus.skype.com/smallicon/' + infohash["skype"] + '" style="border: none;" width="16" height="16" alt="<? echo get_string('callSkype', 'block_presence')?>" /></a>';
	}
	return ret;
}



function print_roster()
{
	var rosterelem = document.getElementById('contact-list');
	var foldedroster = document.getElementById('folded-contact-list');
	var foldmenu = document.getElementById('fold-menu');
	var otherusers = 0;
	if (roster && roster.length)
		otherusers = roster.length-1; // disregard ourselves

	if (otherusers > 0)
		foldedroster.innerHTML = otherusers + (otherusers == 1 ? ' user' : ' users') + ' present';
	else
		foldedroster.innerHTML = '<? echo get_string('chatMsgAlone', 'block_presence')?>';

	foldmenu.innerHTML = expand_link(foldedroster.style.display);
	
	var buf = '';
	for (var i = 0; i < roster.length; i++)
	{
		if (roster[i] == myself && debug == 0)
			continue;

		var rosterentry_specifics = document.getElementById(roster[i] + "_roster_entry");
		if (rosterentry_specifics)
			rosterentry_specifics = rosterentry_specifics.innerHTML;
		else
			rosterentry_specifics = '';

		buf += '<div style="margin:0 auto; text-align:left; font-size:100%;" id="menu-users-list-'+roster[i]+'">';
		//buf += '&raquo; ';
		if (av_enabled)
			buf += '<span style="padding:1px;"><a href="javascript:void(0);" onclick="javascript:avchat(\'' + roster[i] + '\'); return false;" title="<? echo get_string('chatInviteToAVC', 'block_presence')?>"><img src="<?php echo $CFG->baseurl ?>/jwc/covchat-icon3_16x16.png" border="0" /></a></span>';
		if (wb_enabled && wb_active)
			buf += '<span style="padding:1px;"><a href="javascript:void(0);" onclick="javascript:whiteboard(\'' + roster[i] + '\', wb_id); return false;" title="<? echo get_string('chatInviteToWhiteB', 'block_presence')?>"><img src="<?php echo $CFG->baseurl ?>/lullacons/photo-multiple.png" border="0" /></a></span>';
		if (roster_info[roster[i]])
			buf += format_info(roster_info[roster[i]]);
		
		buf += '<span style="width: 16px" id="' + roster[i] + '_roster_entry">' + rosterentry_specifics + '</span>';
		
		buf += '&nbsp;<a href="javascript:void(0);" onclick="javascript:new_window(\'' + roster[i] + '\'); return false;">' + usernames[roster[i]] + '</a>';
		buf += "</div>";
	}
	
	if(roster.length > 0 && buf != "")
	{
		$("#groupchat-title-users").show();
	}else
		$("#groupchat-title-users").hide();
		
	rosterelem.innerHTML = buf;
}

// remains from the jabber stuff, was used to clean JID for display
function clean_name(n)
{
	var slpl = n.indexOf('/');
	return n.substr(0, slpl);
}

function handle_message(msgobj)
{
	// check the msgobj['to'] ... if it's our userid, then the window name shall be the "from" attribute
	// otherwise it shall be the "to" attribute, as this is most likely a group chat..
	var mywin;
	var mywinname;

	if (msgobj['to'] == '<?php echo $USER->username?>')
		mywinname = msgobj['from'];
	else
		mywinname = msgobj['to'];

	mywin = get_window(mywinname);

	if (!mywin)
		mywin = new_window(mywinname);
	
	// XXX: messy hack, this problem might call for a redesign of the conversation
	// object, so that the entry form is not part of it, etc?
	// we might have a message being typed into the window which our message
	// is entering..
	//var tmsg = document.getElementById(mywinname + '_ef').value;
	
	if($("#"+mywin.w).css("display") == "none")
		$("#"+mywin.w).show().dialog("open");

	mywin['c'].newmessage(msgobj['from'], msgobj['message'], msgobj['timestamp']);
	$("#"+mywin['w']+"_conv").empty().append(mywin['c'].render());
	mywin['c'].fixscroll();

	///$("#"+mywinname + '_ef').value = tmsg;
	//if (tmsg != '')
	//	document.getElementById(mywinname + '_ef').focus();
	
	// if the window is minimized.. alert the user somehow?
	if ($("#"+mywinname).css("display") == 'none')
	{
		dalert("message to minimized window: " + mywinname);
		var rosterentry = document.getElementById(mywinname + '_roster_entry');
		rosterentry.innerHTML = '<img src="<?php echo $CFG->baseurl?>/lullacons/alert.png" />';
		intervaler(mywinname+'_roster_entry','<img src="<?php echo $CFG->baseurl?>/lullacons/mini-comment.png" width="16" height="16" />', '<img src="<?php echo $CFG->baseurl?>/lullacons/alert.png" />', 11);
	}
}

function intervaler(elemn,val1,val2,times)
{
	var elem = document.getElementById(elemn);
	if (times > 0)
	{
		elem.innerHTML = val1;
		times--;
		setTimeout("intervaler('"+elemn+"','"+val2+"','"+val1+"',"+times+")", 400);
	}
}

function update_groupchatmenu()
{
	// construct the group chat selection menu..
	var buf = '';
	for (var i = 0; i < roster.length; i++)
	{
		if (roster[i] == myself && debug == 0) // skip over ourselves unless in debug mode
			continue;

		buf += '<div class="divUsersList"><label><input type="checkbox" class="chatUsersList" name="group_' + i + '" value="' + roster[i] + '" />' + roster[i] + '</label></div>';
	}
	
	$("#groupchat-menu>#groupchat-menu-users").empty().append(buf);
}

function groupchat(e)
{
	var	chatW = 300;
	var chatH = 298;

	update_groupchatmenu();

	if(!av_enabled)
		$(".divChatSubmit>input:gt(0)").attr("disabled", "disabled");
	else
		$(".divChatSubmit>input:gt(0)").attr("disabled", "");	

	if($('#groupchat-menu>#groupchat-menu-users').find("input[type=checkbox]").length > 0)
	{

		$('#groupchat-menu').show().dialog(
		{
			title : '<? echo get_string('chatTypeSelect', 'block_presence')?>',
			modal:true,
			width : chatW,
			height: chatH,
			minWidth: chatW,
			minHeight: chatH,
			maxWidth: chatW,
			maxHeight: chatH,
			dragStart: function()
			{
				$(this).css("opacity", .5).find("#groupchat-menu").hide();
			},
			dragStop: function()
			{
				$(this).css("opacity", 1).find("#groupchat-menu").show();
			},
			close: function()
			{
				hide_groupchat()
			},
			overlay:{
				background: "#fff",
				opacity: .6
			}
		})
		.bgiframe();
	}else
		alert('<?php echo get_string('chatNoUsers', 'block_presence')?>');
	
}

function hide_groupchat()
{
	$("#groupchat-menu:visible").dialog("destroy");
}

function save_conv(wname)
{
	if (confirm("<? echo get_string('chatMsgSaveConversation', 'block_presence')?>"))
	{
		var win = get_window(wname);
		var conv = to_json(win.c.messages);
		window.open('<?php echo $CFG->saver_path?>?action=saveconv&conv=' + conv, '', '');
	}
}



var in_updateroster = 0;
var ssack = new sack('<?php echo $CFG->saver_path ?>'); // sack object for sending
var mysack = new sack('<?php echo $CFG->ajwrap_path ?>'); // sack object for various stuff
var psack = new sack('<?php echo $CFG->ajwrap_path ?>'); // sack object for polling
var room = "course_<?php echo $COURSE->id?>";
<?php
// code to see if we're in a subroom... (PR_ACTIVITY is set by weblib.php)
if ($PR_ACTIVITY) {
?>
var subroom = encodeURIComponent("resource_<?php echo $_SERVER['REQUEST_URI']?>");
<?php
} else {
?>
var subroom = '';
<?php
}
?>

// variable used to make sure mysack doesn't get used while
// waiting on readystate 4
var send_wait = 0;

var messages = new Array(); // messages pending sending..
var sent_messages = new Array();

var invites = new Array(); // invites pending sending..

// AJAX functions below

function send_cb()
{
	// XXX: handle errors...
	var resp = from_json(this.response);

	if (resp.ok)
	{
		// sending worked, lets update our windows, and clear the messages array..
		for (var i = 0; i < sent_messages.length; i++)
		{
			var msg = sent_messages[i]['message'];
			wc = get_window(sent_messages[i]['to']);
			
			wc['c'].mymessage(msg, resp.timestamp);
			$("#"+wc['w']+"_conv").empty().append(wc['c'].render());
			wc['c'].fixscroll();
		}
		sent_messages = new Array();
		send_wait = 0;
		status_msg('<? echo get_string('dbgSendCompl', 'block_presence')?>');
	}
	mysack.resetData();
}

function send()
{
	if (!send_wait)
	{
		status_msg('<? echo get_string('dbgSending', 'block_presence')?>');
		send_wait = 1;
		mysack.setVar('msg', to_json({messages: messages}));
		mysack.setVar('type', 'send');
		getreq(mysack, send_cb);
		sent_messages = messages;
		messages = new Array();
	}
	else
	{
		status_msg('<? echo get_string('dbgWaitSend', 'block_presence')?>');
		setTimeout("send()", 2000);
	}
}

// invite functions, for whiteboard, and possibly group chat?
function invite_cb()
{
	mysack.resetData();
	if (this.response)
	{
		var resp = from_json(this.response);
		dalert("invite response: " + this.response);
		if (resp.ok)
		{
			if (resp.type == 'groupchat')
			{
				join(resp.groupid);
			}
		}
		send_wait = 0;
		status_msg('');
	}
}

// uid = target user to send the invite
// type = type of invite whiteboard / groupchat
// groupid = groupid, unique id for global 
function invite(uids, type, groupid, make)
{
	if (invites.length > 0)
	{
		invites.push([uids, type, groupid]);
		var i = invites.shift();
		uids = i[0];
		type = i[1];
		groupid = i[2];

	}
	
	if (!send_wait)
	{
		status_msg('<? echo get_string('dbgSendInvite', 'block_presence')?>');
		send_wait = 1;
		mysack.setVar('invite', to_json({type: type, to: uids, groupid: groupid}));
		mysack.setVar('type', 'invite');
		getreq(mysack, invite_cb);
		sent_messages = messages;
		messages = new Array();
	}
	else
	{
		status_msg('<? echo get_string('dbgWaitSend', 'block_presence')?>');
		setTimeout("invite()", 2000);
	}
	
	if (type == 'whiteboard')
	{
		// nothing needs to be done.. the whiteboard is already running locally
	}
	
	if(make) 
	{
		makeConference(uids, type, groupid);
	}else
	{
		$("#"+groupid).dialog('open')
	}
}

function makeConference(uids, type, groupid) {
	// AVChat accepts the usernames for displaying from us, so lets provide the real one
	// now we use uids as a string! ?! ... this will need changes for groupchat, fix later
	var users = new Array();
	//console.log("to uids=", typeof(uids), "uids.c=", uids.constructor);
	if (typeof(uids) == "object" && uids.constructor == Array)
	{
		//console.log("it's an array");
		// uids is an array, lets rebuild it from the usernames array
		for (var i = 0; i < uids.length; i++)
		{
			//console.log("and username", i, " =", usernames[uids[i]]);
			if (usernames[uids[i]])
				users.push(usernames[uids[i]]);
			else
				users.push(uids[i]);
		}
	}
	else
	{
		if (usernames[uids])
			users = usernames[uids];
		else
			users = uids;
	}

	if(type.indexOf('avchat') >= 0)
	{
		if(type == 'avchat')
		{
			status_msg('<? echo get_string('dbgOpenLocAV', 'block_presence')?>');
			var chatUrl = '<?php echo $CFG->wwwroot?>/covavchat/invite.php?userid=' + users + '&ticket=' + groupid
			var chatTitle= ':: <? echo get_string('videoConference', 'block_presence')?> ::'
		}else
		{
			if(type == 'avchatmoderated')
			{
				status_msg('<? echo get_string('dbgOpenLocAVMod', 'block_presence')?>');
				var chatUrl = '<?php echo $CFG->wwwroot?>/covavchat/invite.php?userid=' + users + '&ticket=' + groupid + '&moderated=true'
				var chatTitle= ':: <? echo get_string('moderatedAV', 'block_presence')?> ::'
			}
			else
			{
				alert('<? echo get_string('avTypeInvalid', 'block_presence')?>')
				return false;
			}
		}
		
		openIframeWindow(chatUrl, chatTitle, null, null, groupid)
	}
}

function openIframeWindow(url, title, width, height, winID)
{
	var winID	= winID ? winID : "avchatUI"
	var title	= title ? title : "";
	var width	= width  ? width : 640;
	var height	= height ? height : 480;
	
	if($("#"+winID).length <= 0)
	{ 
		$("body").prepend($('<div id="'+winID+'" class="flora">'));
		$("#"+winID).append(
			$("<iframe>")
				.attr({"name" : winID+"_avchatFrame",
						"id":   winID+"_avchatFrame",
						frameborder: "0"
						})
				.css({
					width : width - 18,
					height: height - 35,
					border : "0px"
				})
		);

		$("#"+winID).dialog({
		    	title : title,
		    	width : width,
		    	height: height,
				dragStart: function()
		    	{
		    		$(this).find("iframe").css("visibility", "hidden");
		    	},
		    	dragStop: function()
		    	{
		    		$(this).find("iframe").css("visibility", "visible");
		    	},
		    	resizeStart: function()
		    	{
		    		$(this).find("iframe").css("visibility", "hidden");
		    	},
		    	resizeStop: function()
		    	{
		    		$(this).find("iframe").width($(this).width() - 18)
		    		$(this).find("iframe").height($(this).height() - 35)
		    		$(this).find("iframe").css("visibility", "visible");
		    	},
		    	close: function()
		    	{
		    		
		    	}
		}).bgiframe();
	}

	if(url)
		$("#"+winID+"_avchatFrame").attr("src",  url);

	$("#"+winID).dialog("open");

}


function login_cb()
{
	if (this.response)
	{
		var resp = from_json(this.response);
		if (resp.ok)
		{
			logged_in = 1;
		}
		else
		{
			dalert("<? echo get_string('dbgLoginFailed', 'block_presence')?>: " + resp.error);
		}
	}
	else
		dalert("<? echo get_string('dbgLoginFailed', 'block_presence')?>: <? echo get_string('dbgLoginFailedUnk', 'block_presence')?>");

	mysack.resetData();
}

function login(username, password)
{
	mysack.setVar('type','login');
	mysack.setVar('uid',username);
	mysack.setVar('password',password);
	getreq(mysack, login_cb);
}

function updateroster_cb()
{
	in_updateroster = 0;
	var resp = from_json(this.response);
	if (resp.ok)
	{
		roster_info = from_json(decodeURIComponent(resp.extra));
	}
	// update usernames lookup table (username -> realname)
	for (username in roster_info)
	{
		var rosterentry = roster_info[username];
		if (rosterentry['firstname'] || rosterentry['lastname'])
			usernames[username] = rosterentry['firstname'] + ' ' + rosterentry['lastname'];
		else
			usernames[username] = username;
	}

	

	print_roster();
	ssack.reset();
}

function updateroster()
{
	print_roster(); // call it here anyway, the html needs to be there?!

	if (in_updateroster == 1) // we check now because it's ok to print the roster again just in case..
		return;

	in_updateroster = 1;

	ssack.reset();
	ssack.requestFile = '<?php echo $CFG->baseurl?>/jwc/userinfo.php';
	for (i = 0;i < roster.length; i++)
	{
		ssack.setVar('usernames[' + i +']', roster[i]);
	}
	getreq(ssack, updateroster_cb);
}

function wb_window(url)
{
	title = "<? echo get_string('whiteBoard', 'block_presence')?>";
	width  = 675;
	height = 545;
	
	if($("#whiteboardWindow").length <= 0)
	{ 
		$("body").prepend($('<div id="whiteboardWindow" class="flora">'));
		$("#whiteboardWindow").append(
			$("<iframe>")
				.attr({"name" : "whiteboardWindowIfr",
						"id":   "whiteboardWindowIfr",
						frameborder: "0",
						"scrolling": "no"
						})
				.css({
					width : width - 18,
					height: height - 35,
					border : "0px"
				})
		);
		
		$("#whiteboardWindow").dialog({
		    	title : title,
		    	width : width,
		    	height: height,
				dragStart: function()
		    	{
		    		$(this).find("iframe").css("visibility", "hidden");
		    	},
		    	dragStop: function()
		    	{
		    		$(this).find("iframe").css("visibility", "visible");
		    	},
		    	resizeStart: function()
		    	{
		    		$(this).find("iframe").css("visibility", "hidden");
		    	},
		    	resizeStop: function()
		    	{
		    		$(this).find("iframe").width($(this).width() - 18)
		    		$(this).find("iframe").height($(this).height() - 35)
		    		$(this).find("iframe").css("visibility", "visible");
		    	},
		    	close: function()
		    	{
		    		$(this).find("destroy");
		    	}
		});
		
		$("iframe#whiteboardWindowIfr").attr("src", url);
	}else
	{
		$("#whiteboardWindow").dialog("open");
	}
}

function poll_cb()
{
	var resp = from_json(this.response);

	if (!resp.ok)
	{
		dalert("Got bad response from poll! Will reschedule poll, hope it works.\nthis.response=" + this.response);
		setTimeout("poll()", 2000);
		return;
		//return login('<?php echo $USER->username?>','<?php echo $USER->username?>');
	}

	// maybe we need to update the roster stuff...
	if (resp.roster)
	{
		if (resp.roster.length > 0)
		{
			roster = resp.roster;
			// XXX: check if roster differs from current roster before redrawing to reduce flickering?
			updateroster();
		}
	}

	// lets handle the messages
	if (resp.messages && resp.messages.length > 0)
	{
		for (var i = 0; i < resp.messages.length; i++)
		{
			handle_message(resp.messages[i]);
		}
	}

	// lets handle the invites
	if (resp.invites && resp.invites.length > 0)
	{
		for (var i = 0; i < resp.invites.length; i++)
		{
			if (resp.invites[i].type == 'whiteboard')
			{
				if (confirm(resp.invites[i].from + ' <? echo get_string('invWb', 'block_presence')?>'))
				{
					hide_groupchat();

					// we call setTimeout and return here since if firefox blocks a popup window
					// from opening the function in which the block occurs stops executing all-
					// together, so the setTimeout in wider scope is never executed.
					// XXX: problem, if you have multiple invites being handled, the rest will be ignored..
					setTimeout("poll()", 2000);
					wb_window('<?php echo $CFG->baseurl?>/../../../mod/cwhiteboard/whiteboard.php?id=' + resp.invites[i].groupid + '&type=user', 'wb_' +resp.invites[i].from + '_' + resp.invites[i].groupid)
					///return openpopup('/mod/cwhiteboard/whiteboard.php?id=' + resp.invites[i].groupid + '&type=user', 'wb_' +resp.invites[i].from + '_' + resp.invites[i].groupid, 'menubar=0,location=0,width=650,height=520,resizable', 0);
				}
			}
			else if (resp.invites[i].type == 'groupchat')
			{
				if (confirm(resp.invites[i].from + ' <? echo get_string('invGroupChat', 'block_presence')?>'))
				{
					hide_groupchat();
					// send a join request to join the groupchat etc..
					join(resp.invites[i].groupid);				
				}
			}
			else if(resp.invites[i].type == 'avchat')
			{
				if(confirm(resp.invites[i].from + ' <? echo get_string('invAVChat', 'block_presence')?>'))
				{
					hide_groupchat();
					
					setTimeout("poll()", 2000);
					return openIframeWindow('<?php echo $CFG->wwwroot?>/covavchat/accept_invitation.php?token=' + resp.invites[i].groupid, 'Videoconferencia')
					//openpopup('/covavchat/accept_invitation.php?token=' + resp.invites[i].groupid);
				}
			}
			else if(resp.invites[i].type == 'avchatmoderated')
			{
				if(confirm(resp.invites[i].from + ' <? echo get_string('invAVChat', 'block_presence')?>'))
				{
					hide_groupchat();

					setTimeout("poll()", 2000);
					return openIframeWindow('<?php echo $CFG->wwwroot?>/covavchat/accept_invitation.php?token=' + resp.invites[i].groupid+ '&moderated=true', 'Videoconferencia')
					//return openpopup('/covavchat/accept_invitation.php?token=' + resp.invites[i].groupid + '&moderated=true');
				}
			}

		}
	}

	setTimeout("poll()", 2000);
}

function poll()
{
	if (logged_in)
	{
		psack.setVar('type','poll');
		psack.setVar('room',room);
		psack.setVar('subroom',subroom);
		getreq(psack, poll_cb);
	}
}

function save_data_cb()
{
//	var resp = from_json(this.response);
//	if (resp.ok == 0)
//	{
//		alert("failed to save data (" + resp.extra + ")");
//	}
}

function save_data(data)
{
	if (logged_in)
	{
		//alert("save_data");
		//console.log("saving data??");
		ssack.reset();
		ssack.setVar('action','set');
		ssack.setVar('sessinfo', encodeURIComponent(data));
		getreq(ssack, save_data_cb);
	}
}

function get_data_cb()
{
	//alert(this.response);
	var resp = from_json(this.response);
	var mydata = {};

	if (resp.ok)
	{
		dalert(resp.extra);
		mydata = from_json(decodeURIComponent(resp.extra));
		dalert(mydata);
	}
	else
	{
		//login('<?php echo $USER->username?>','<?php echo $USER->username?>');
	}

	//dalert(mydata.s);
	if (mydata)
	{
		if (!resp.ok)
			return;
		// set the data!! WOOHOO
		var c = mydata.c;
		roster = mydata.r;
		if (mydata.wb)
		{
			wb_active = mydata.wb['active'];
			if (mydata.wb['id'])
				wb_id = mydata.wb['id'];
		}

		updateroster();
		
		//alert("got data, updated roster, now about to make windows...");
		//console.log("about to create windows! c.length=" + c.length);

		for (var i = 0; i < c.length; i++)
		{
			var cobj = c[i];
			var win = new_window(cobj['wname']);
			


			if (cobj['vis'] == 0)
				minimize_window(cobj['wname']);

			win.ouruser = cobj.conv['ouruser'];
			win.otheruser = cobj.conv['otheruser'];
			win.c.messages = cobj.conv['messages']
			///win.w.setbody(win.c.render());
			win.c.fixscroll();
		}
	}
	else
	{
		//login('<?php echo $USER->username?>','<?php echo $USER->username?>');
	}
}

function get_data()
{
	ssack.setVar('action','get');
	getreq(ssack, get_data_cb);
}

function save_all_data()
{
	var conversations = new Array();
	for (i = 0; i < open_wins.length; i++)
	{
		var visible = 1;
		if ($("#"+open_wins[i]).css("display") == 'none')
			visible = 0;

		conversations.push({
					wname: open_wins[i].w,
					//w_h: windows[open_wins[i].w['wname']],
					conv: { ouruser: open_wins[i]['c']['ouruser'],
						otheruser: open_wins[i]['c']['otheruser'],
						messages: open_wins[i]['c']['messages'] },
					//pos: window_position(open_wins[i].w['wname']),
					vis: visible})
	}
//	alert("save_all_data");
	save_data(to_json({c: conversations, r: roster, wb: {active: wb_active, id: wb_id}}));
}

function start_groupchat(chatType)
{
	// lets gather data from the groupchat form
        //var f = document.forms.groupchatform;
        var guests = new Array();
        var chatType = chatType ? chatType : "text";
		var checkBoxUsers = $(".chatUsersList:checked");
		if(checkBoxUsers.length == 0)
		{
			alert("<?php echo get_string('noUsersSelected', 'block_presence')?>");
		}else
		{
			checkBoxUsers.each(function()
			{
				guests.push(this.value);
			});
			
			dalert('guests=' + guests.toString());

			
			if(chatType == "text"){
				invite(guests, 'groupchat', '<?php echo $USER->username?>groupchat');
			} else if(chatType == "av"){
			// mudando o token
			avToken = LightweightGenerator.generate();        
				invite(guests, 'avchat', avToken, true);
			} else if(chatType == "avmoderated"){
			avToken = LightweightGenerator.generate();        
				invite(guests, 'avchatmoderated', avToken, true);
			}else if(chatType == "whiteboard")
			{
				invite(guests, 'whiteboard', avToken, true);
			}
			
			hide_groupchat();
		}
}


function whiteboard(uid, groupid)
{
	invite([uid], 'whiteboard', groupid);
}

function avchat(uid)
{
	make = false;	
	if(!avToken) {
	    avToken = LightweightGenerator.generate();
	    var make = true;        
	}
	invite([uid], 'avchat', avToken, make);
}


function join_cb()
{
	var resp = from_json(this.response);
	dalert("join response:" + this.response);

	if (resp.ok)
	{
		new_window(resp.room);
	}
	mysack.resetData();
}

function join(groupid)
{
	dalert("about to join groupchat: " + groupid);
	mysack.setVar('type','join');
	mysack.setVar('room',groupid);
	getreq(mysack, join_cb);
}

// before logging in.. we should check if we have an open session, etc.. try the get_data call.
get_data();
window.onunload = save_all_data;
//myBody = document.getElementsByTagName("body")[0];
//myBody.addEventListener('beforeunload', save_all_data, false);; // hack to work in safari as well

setTimeout("poll()", 500);



/** NOVAS FUNÇÕES **/
/** Marca/Desmarca todas as checkboxes **/
function checkAVCUsers(action)
{
	var Boxes = $('#groupchat-menu-users').find('input[type=checkbox]');
	
	if(action=='uncheck')
	{
		$(".formChatSelect a:last").hide();
		$(".formChatSelect a:first").show();
		
		Boxes.attr("checked", "");
	}else
	{
		$(".formChatSelect a:first").hide();
		$(".formChatSelect a:last").show();
		
		Boxes.attr("checked", "checked");
	}
	/*Boxes.each(function()
	{
		if(this.checked == "")
			this.checked = "checked"
		else
			this.checked = ""
	})*/
}
</script>
<style type="text/css">
<?php
/** If we're running in activity mode, we'll need to add some stylesheet information to curb our enthusiasm
*/
if ($PR_ACTIVITY == 1)
{
?>
#presence-block
{
	width: 250px;
	float: left;
	border-left: 1px solid black;
	border-right: 1px solid black;
	border-bottom: 1px solid black;
}
#contact-list
{
	text-align: left;
	display: none;
}
#folded-contact-list
{
	display: block;
	text-align: left;
	font-family: Verdana;
	font-size: 10px;
	font-weight: bold;
	color: #fff;
	background-image: url(<?php echo $CFG->baseurl?>jwc/covc2.png);
	background-repeat: no-repeat;
	background-position: top left;
	height: 31px;
	padding-top: 9px;
	padding-left: 40px
}
#fold-menu
{
	display: block;
	text-align: left;
}
<?php
} else {
?>
#folded-contact-list, #fold-menu
{
	display: none;
}
<?php
}
?>
#groupchat-menu
{
	margin:0 auto;
	text-align:left;
	display: none;
	padding:10px;
}
#groupchat-menu li
{
	font-size:50%;
}

#groupchat-menu-users
{
	width:100%;
	height:120px;
	background:#fff;
	border:1px #dedede solid;
	overflow:auto;
}

.divChatSubmit
{
	width:100%;
	padding:2px;
}

.formChatSelect
{
	margin:0 auto;
	text-align:right;
}

#status-layer
{
	height: 20px;
	background-color: #77f;
	display: block;
	font-size:90%;
	color:#fff;
}

.divUsersList
{
	padding:2px;
}

.buttonChatType
{
	background-image:url('<? echo $CFG->baseurl?>/jwc/jquery/ui/themes/flora/i/bg.png');
	width:100%;
	background-repeat:repeat-x;
	background-position:center center;
	cursor:pointer;
	font-size:100%;
	font-family:arial;
}
</style>
<div id="presence-block">
	<!-- Status Layer - this is for debugging only --> 
	<div id="status-layer"></div> 
	<div id="presenceLinks" style="margin:0 auto; text-align:left;">
		<div>&raquo;&nbsp;<a href="javascript:void(0);" onclick="groupchat(event)"><?php echo get_string('startGroupChat', 'block_presence')?></a></div>
		<?php if($CFG->cp_wb_link):?>
		<div>&raquo;&nbsp;<a href="javascript:void(0);" onclick="wb_window('<?php echo $CFG->baseurl?>/../../../mod/cwhiteboard/new.php')" id="wblink"><?php echo get_string('startWhiteBoard', 'block_presence')?></a></div>
		<?endif;?>
	</div>
	
	<div id="folded-contact-list"></div>
	<div id="groupchat-title-users" style="display:none;font-weight:bold; padding-top:5px;"><?php echo get_string('chatUsers', 'block_presence')?>:</div>
	<div id="contact-list"></div>
	<div id="fold-menu"></div>

	<div id="groupchat-menu" class="flora">
		<div class="formChatSelect">
			<div style="float:left;">
				<b><? echo get_string('chatUsers', 'block_presence')?>:</b>
			</div>
			<div style="float:right;">
				<a href="#" onclick="checkAVCUsers('check')"><? echo get_string('formSelectAll', 'block_presence')?></a>
				<a href="#" onclick="checkAVCUsers('uncheck')" style="display:none;"><? echo get_string('formSelectNone', 'block_presence')?></a>
			</div>
		</div>

		<div id="groupchat-menu-users"></div>
		
		<div style="padding-top:5px;">
			<b><? echo get_string('chatTypeSelect', 'block_presence')?>:</b>
		</div>
		<div class="divChatSubmit">
			<input type="button" class="buttonChatType" onclick="start_groupchat('text')" value="<? echo get_string('textChat', 'block_presence')?>" /><br />
			<input type="button" class="buttonChatType" onclick="start_groupchat('avmoderated')" value="<? echo get_string('chatAVModerated', 'block_presence')?>" /><br />
			<input type="button" class="buttonChatType" onclick="start_groupchat('av')" value="<? echo get_string('chatAV', 'block_presence')?>" />
		</div>
	</div>	
</div>
